#By Daoyu @2010-07-28

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from uncle.users.models import *
from uncle.project.models import *
from uncle.util.page import *

def project_asset_to_basket(project, asset):
    b = Basket()
    b.type = asset.type
    b.title = asset.title
    b.hide = True
    b.url = asset.url
    b.text = asset.text
    b.project = project
    b.user = asset.user
    b.save()

#-------------------------------------------------------------------------------
# Add a video to a basket.
#-------------------------------------------------------------------------------
@login_required
def add(request):
    if request.user.has_perm('users.is_producer'):        
        project = Project.objects.get(id=request.POST['basket'])
        v = video.objects.get(id=request.POST['v_id'])
        project_asset_to_basket(project, v)

@login_required
def assets(request, uid):
    if request.user.has_perm('users.is_producer'):
        assets = video.objects.filter(user__id=uid)
        bas = Project.objects.filter(creator__id = request.user.id)
        from uncle.util.util import asset_avatar
        asset_avatar(assets)
        
        return render_to_response('user/assets.html',
            {'assets':assets, 'bas':bas },
            context_instance = RequestContext(request))

@login_required
def add_assets(request):
    pid = int(request.POST['basket'])
    project = Project.objects.get(id=pid)
    if request.user.has_perm('users.is_producer') and project.creator.id == request.user.id and request.method=='POST':
        assets = request.POST.getlist("selected_asset")
        for a in assets:
            aid = int(a)
            v = video.objects.get(id=aid)
            
            project_asset_to_basket(project, v)
    return HttpResponse("success")
    
def delete_basket(request,b_id):
    if request.user.has_perm('users.is_producer'):
        Basket.objects.filter(id = b_id).delete()
        request.user.message_set.create(message = 'Basket deleted')
    return HttpResponseRedirect('/user/basket/')
